package com.drm.netschool.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.drm.common.util.ConfigUtil;
import com.drm.common.util.CookieUtil;
import com.drm.common.util.NumberUtil;
import com.drm.common.util.PriceUtils;
import com.drm.common.util.StringUtil;
import com.drm.common.util.constants.Constants;
import com.drm.netschool.entity.DrmBuyCart;
import com.drm.netschool.entity.DrmUser;
import com.drm.netschool.entity.extend.CartInfo;
import com.drm.netschool.service.DrmBuyCartService;
import com.drm.netschool.service.DrmCourseService;
import com.drm.netschool.service.DrmSalesPromotionService;
import com.drm.netschool.service.DrmStudyCoinService;
import com.drm.netschool.service.DrmSystemSettingService;
import com.drm.netschool.service.DrmUserCacheService;
import com.drm.netschool.service.DrmUserSinfoService;
import com.drm.netschool.web.annotation.AccessRequired;
import com.drm.netschool.web.form.CartForm;


@Controller
@RequestMapping("/cart/")
public class CartController {

	private Logger LOGGER = LoggerFactory.getLogger(AreaController.class);
	
	@Autowired
	private DrmBuyCartService cartService;
	
	@Autowired DrmCourseService courseService;
	
	@Autowired
	private DrmUserCacheService userCacheService;
	
	@Autowired
	private DrmUserSinfoService userInfoService;
	
	@Autowired
	private DrmSalesPromotionService promotionService;
	
	@Autowired
	private DrmSystemSettingService systemSettingService;
	
	@Autowired
	private DrmStudyCoinService studyCoinService;
	
	@RequestMapping(value = "count", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getCount(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		DrmUser user = null;
		CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
    	if(!StringUtil.empty(key))
    		user = userCacheService.getUserCache(key);
    	
    	int count = 0;
    	if(user != null){
    		DrmBuyCart cart = new DrmBuyCart();
    		cart.setUserId(user.getUserId());
    		cart.setCartSt(1);
    		cart.setCartTp(0);
    		count = cartService.getCount(cart);
    	}
    	result.put("count", count);
		return result;
	}
	
	@AccessRequired
	@RequestMapping(value = "list")
	public String list(@ModelAttribute("form") CartForm form, HttpServletRequest request, HttpServletResponse response){
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		
		CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
    	DrmUser user = userCacheService.getUserCache(key);
    	if(user == null){
    		return "login/login";
    	}
    	//查询购物车列表
    	CartInfo cart = new CartInfo();
		cart.setUserId(user.getUserId());
		cart.setCartSt(1);
		if(form.getCart() != null && NumberUtil.parseLong(form.getCart().getCartId()) > 0)	//立即下单的课程
			cart.setCartId(form.getCart().getCartId());
		else	//加入购物车中的课程
			cart.setCartTp(0);
		List<CartInfo> cartList = cartService.getCartList(cart);
		form.setCartList(cartList);
		
		//查询优惠券
		form.setPromotion(promotionService.getPromotion(1));
		form.setUserInfo(userInfoService.getByUserId(user.getUserId()));
		form.setStudyCoin(studyCoinService.getDrmStudyCoin());
		return "cart/list";
	}
	
	@AccessRequired
	@RequestMapping(value = "confirm", method = RequestMethod.POST)
	public String confirmCart(@ModelAttribute("form") CartForm form, HttpServletRequest request, HttpServletResponse response){
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		
		CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
    	DrmUser user = userCacheService.getUserCache(key);
    	if(user == null){
    		return "login/login";
    	}
    	//查询购物车列表
		CartInfo cart = new CartInfo();
		cart.setUserId(user.getUserId());
		cart.setCartSt(1);
//		cart.setCartTp(0);
		List<CartInfo> cartList = cartService.getCartList(cart, form.getIdsList());
		form.setCartList(cartList);
		
		
		//查询优惠券
		form.setPromotion(promotionService.getPromotion(1));
		if(form.isUseState()){
			form.setUserInfo(userInfoService.getByUserId(user.getUserId()));
			form.setStudyCoin(studyCoinService.getDrmStudyCoin());
		}
		return "shop/list";
	}
	
	@AccessRequired
	@RequestMapping(value = "del/{cartId}/{courseId}", method = RequestMethod.GET)
	public Map<String, Object> del(@PathVariable Long cartId, @PathVariable Long courseId, HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
	    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
	    	DrmUser user = userCacheService.getUserCache(key);
	    	if(user == null){
	    		result.put("status", "用户未登录!");
	    		return result;
	    	}
	    	int r = cartService.delById(cartId, courseId);
	    	if(r == 0)
	    		result.put("status", "购物车删除商品失败!");
	    	else
	    		result.put("status", "200");
		} catch (Exception e) {
			LOGGER.error(courseId + "购物车删除商品异常", e);
			result.put("status", "系统异常!");
		}
		return result;
	}
	
	@AccessRequired
	@RequestMapping(value = "add/{type}/{courseId}", method = RequestMethod.GET)
	public String add(@PathVariable Integer type, @PathVariable Long courseId, HttpServletRequest request, HttpServletResponse response){
		Long cartId = null;
		try {
			CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
	    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
	    	DrmUser user = userCacheService.getUserCache(key);
	    	if(user == null){
	    		return "login/login";
	    	}
	    	cartId = cartService.add(user.getUserId(), courseId, type);
		} catch (Exception e) {
			LOGGER.error(courseId + "添加课程异常", e);
		}
		return type == 1 ? "redirect:/cart/list?cart.cartId=" + cartId : "redirect:/cart/list";
	}
	
	@AccessRequired
	@RequestMapping(value = "addCart/{type}/{courseId}", method = RequestMethod.GET)
	public Map<String, Object> addCart(@PathVariable Integer type, @PathVariable Long courseId, HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
	    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
	    	DrmUser user = userCacheService.getUserCache(key);
	    	if(user == null){
	    		result.put("status", "没有用户信息");
	    	}
	    	cartService.add(user.getUserId(), courseId, type);
	    	
	    	//查询购物车列表
	    	CartInfo cart = new CartInfo();
			cart.setUserId(user.getUserId());
			cart.setCartSt(1);
			cart.setCartTp(0);
			List<CartInfo> cartList = cartService.getCartList(cart);
			Long amount = 0l;
			if(cartList != null){
				for(CartInfo c : cartList){
					amount += NumberUtil.parseLong(c.getCurPrice());
				}
			}
	    	result.put("status", "200");
	    	result.put("size", cartList == null ? 0 : cartList.size());
	    	result.put("amount", PriceUtils.intToStr(amount.intValue()));
		} catch (Exception e) {
			LOGGER.error(courseId + "添加课程异常", e);
			result.put("status", "添加课程异常");
		}
		return result;
	}
}
